package com.kye.express.business.invoice_online.tab;

import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.invoice_online.detail.InvoiceDetailActivity;
import com.kye.express.databinding.FragmentInvoiceCompanyBinding;
import com.kye.express.databinding.FragmentInvoicePeopleBinding;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.invoice_online.ElectronicInvoiceResultBean;
import com.kye.model.bean.invoice_online.GeneratedInvoiceDataResultBean;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function3;

public class InvoiceInfoPeopleFragment extends BaseAppCompatFragment implements InvoiceInfoFragmentContract.InvoiceInfoFragmentView {
    private static final String ARG_WAYBILLS = "waybills";
    private static final String ARG_PRICE = "price";

    protected FragmentInvoicePeopleBinding mDataBinding;
    private ArrayList<GeneratedInvoiceDataResultBean> mCurrentSelectedWaybillList = new ArrayList<>();
    private double mTotalPrice = 0;
    private InvoiceInfoFragmentContract.InvoiceInfoFragmentViewPresenter mPresenter;
    private Dialog mLoadingDialog;

    public static InvoiceInfoPeopleFragment newInstance(ArrayList<GeneratedInvoiceDataResultBean> generatedInvoiceDataResultBeans, double totalPrice) {
        InvoiceInfoPeopleFragment fragment = new InvoiceInfoPeopleFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARG_WAYBILLS, generatedInvoiceDataResultBeans);
        bundle.putDouble(ARG_PRICE, totalPrice);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_invoice_people, container, false);
        initViews(view, savedInstanceState);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    private void initViews(View view, Bundle savedInstanceState) {
        mDataBinding = DataBindingUtil.bind(view);
        mPresenter = new InvoiceInfoFragmentContract.InvoiceInfoFragmentViewPresenter(getActivity());
        mPresenter.bind(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mCurrentSelectedWaybillList = (ArrayList<GeneratedInvoiceDataResultBean>) bundle.getSerializable(ARG_WAYBILLS);
            mTotalPrice = bundle.getDouble(ARG_PRICE);
        }
        mDataBinding.tvPrice.setText("￥" + mTotalPrice);
        initEvents();
    }

    private void initEvents() {

        Observable<CharSequence> invoiceHeadChange = RxTextView.textChanges(mDataBinding.edtInvoiceHead).cache();

        invoiceHeadChange.subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                mDataBinding.btnSubmit.setEnabled(!(TextUtils.isEmpty(charSequence.toString().trim())));
            }
        });

        RxView.clicks(mDataBinding.btnSubmit)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (checkParams()) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = 0; i < mCurrentSelectedWaybillList.size(); i++) {
                                if (i == 0) {
                                    stringBuilder.append(mCurrentSelectedWaybillList.get(i).getGroupCode());
                                } else {
                                    if (!stringBuilder.toString().contains(mCurrentSelectedWaybillList.get(i).getGroupCode())) {
                                        stringBuilder.append("," + mCurrentSelectedWaybillList.get(i).getGroupCode());
                                    }
                                }
                            }
                            if (mCurrentSelectedWaybillList.size() == 1) {
                                if (mTotalPrice > 10000) {
                                    new MaterialDialog.Builder(getActivity())
                                            .title(R.string.invoice_online_price_limit)
                                            .content(R.string.invoice_online_price_limit_dialog_message)
                                            .positiveText(R.string.invoice_online_split)
                                            .negativeText(R.string.common_cancel)
                                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                    startElectronicInvoice(stringBuilder);
                                                }
                                            })
                                            .show();
                                } else {
                                    startElectronicInvoice(stringBuilder);
                                }
                            } else {
                                startElectronicInvoice(stringBuilder);
                            }
                        }
                    }
                });
    }

    private void startElectronicInvoice(StringBuilder stringBuilder) {
        mPresenter.electronicInvoice(mDataBinding.edtInvoiceHead.getText().toString(),
                2,
                "安卓APP",
                "",
                mDataBinding.edtAddressPhone.getText().toString(),
                "",
                mDataBinding.edtEmail.getText().toString(),
                stringBuilder.toString()
        );
    }

    private boolean checkParams() {
        if (mCurrentSelectedWaybillList.size() < 1) {
            return false;
        }

        if (StringUtils.isNullOrEmpty(mDataBinding.edtInvoiceHead.getText().toString())) {
            showToast(getString(R.string.invoice_online_head_is_null));
            return false;
        }

        if (StringUtils.isNullOrEmpty(mDataBinding.edtInvoiceContent.getText().toString())) {
            showToast(getString(R.string.invoice_online_content_is_null));
            return false;
        }

        String phone = mDataBinding.edtAddressPhone.getText().toString();
        if (!StringUtils.isNullOrEmpty(phone)) {
            if (!StringUtils.isMobileNO(phone)) {
                showToast(getString(R.string.invoice_online_phone_error));
                return false;
            }
        }

        String email = mDataBinding.edtEmail.getText().toString().trim();
        if (!StringUtils.isNullOrEmpty(email)) {
            if (!StringUtils.checkEmail(email)) {
                showToast(getString(R.string.invoice_online_email_error));
                return false;
            }
        }
        return true;
    }

    private void showToast(String message) {
        ToastManager.show(getActivity(), message, Toast.LENGTH_SHORT);
    }

    @Override
    public void onComplete() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(List<ElectronicInvoiceResultBean> datas) {
        if (datas != null && datas.size() > 0) {
            ElectronicInvoiceResultBean electronicInvoiceResultBean = datas.get(0);
            if (electronicInvoiceResultBean != null && (!TextUtils.isEmpty(electronicInvoiceResultBean.getGroupCode())))
                InvoiceDetailActivity.startActivity(getActivity(), electronicInvoiceResultBean.getGroupCode());
        }
    }

    @Override
    public void onApiError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onOtherError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}
